<template>
<div class="management-merchant views-container">
  <el-dialog @close="saveDialogForm" @open="dialogOpen" :visible.sync="dialogTableVisible" custom-class="reset-pwd wlm-form-dialog dialog-table">
    <div class="wlm-form" v-if="dialogTableVisible">
      <div class="wlm-form-header wlm-dialog-fixheader">
        <span class="wlm-dialog-inlenr">{{`${!!formFormatData.api['editForm']['params']['id']?'编辑':'添加'}店员`}}</span>
      </div>
      <el-scrollbar wrap-class="scrollbar-wrapper">
        <div class="wlm-form-content">
          <div class="wlm-dialog-main">
            <div class="wlm-dialog-content">
              <el-form ref="user" :model="formFormatData.formData" :rules="formFormatData.rules" size="small" label-width="120px" class="retail-form" label-position="right">
                <el-form-item label="用户">
                <span v-if="!!formFormatData.api['editForm']['params']['id']">{{formFormatData.formData.nickName}}</span>
                <chooseUser v-else :config="initChooseUser" ref="chooseUser" :changeEvt="userChange">
                  <template slot="el-table-column">
                      <el-table-column label="所属门店" >
                            <template slot-scope="scope">
                                <span>{{ scope.row.bus_name || '-' }}</span>
                            </template>
                      </el-table-column>
                  </template>
                </chooseUser>
                </el-form-item>
                <el-form-item label="姓名">
                  <el-input v-model.trim="formFormatData.formData.name">
                  </el-input>
                </el-form-item>
                <el-form-item label="联系方式">
                  <el-input v-model.trim="formFormatData.formData.mobile">
                  </el-input>
                </el-form-item>
                <el-form-item label="店员身份">
                  <el-radio-group v-model="formFormatData.formData.type" @change="formFormatData.formData.power = [],formFormatData.formData.store_id=''">
                    <el-radio :label="0">店员</el-radio>
                    <el-radio :label="1">管理员</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item v-if="formFormatData.formData.type == 0" label="所属门店" prop="nickname">
                  <el-select filterable v-model="formFormatData.formData.store_id" placeholder="请选择">
                    <el-option v-for="item in selecStoreData" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                  <p class="form-help">管理员不隶属于某个门店</p>
                </el-form-item>
                <el-form-item label="权限">
                  <el-checkbox-group v-model="formFormatData.formData.power">
                    <el-checkbox v-if="formFormatData.formData.type == 0" v-for="role in [{label:'订单核销',value:'hxorder'},
                    {label:'查看交易数据',value:'seedata'}, 
                    {label:'消息通知',value:'takemsg'},
                    {label:'核销记录',value:'look_hx_order'},
                    {label:'自提记录',value:'look_self_order'},
                    {label:'卡包记录',value:'look_card_order'},
                    {label:'订单管理',value:'look_order'},
                    {label:'门店结算数据',value:'store_settlement_data'}]" :label="role.value" :key="role.value">{{role.label}}</el-checkbox>
                    <el-checkbox v-if="formFormatData.formData.type == 1" v-for="role in powerdata" :label="role.value" :key="role.value">{{role.label}}</el-checkbox>
                    <!-- <el-checkbox v-if="formFormatData.formData.type == 1" v-for="role in [{label:'查看交易数据',value:'seedata'}, {label:'接收下单通知',value:'takenot'}]" :label="role.value" :key="role.value">{{role.label}}</el-checkbox> -->
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item label="状态">
                  <el-radio-group v-model="formFormatData.formData.status">
                    <el-radio :label="1">开启</el-radio>
                    <el-radio :label="0">关闭</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="店员核销密码" v-if="formFormatData.formData.type==0">
                  <!-- prop="password" -->
                  <!-- :disabled="!!formFormatData.api['editForm']['params']['id']" -->
                  <el-input :type="passwordType" @input.native="changeCodeF" :maxlength="4" name="password" v-model="formFormatData.formData.password">
                      <template slot="append">
                        <span
                          class="show-pwd"
                          style="cursor: pointer;"
                          @click="showPwd"
                        >
                          <svg-icon :icon-class="passwordType === 'password'?'eye':'showpassword'" />
                        </span>
                      </template>
                  </el-input>
                  <p class="form-help">用于用户自助核销，密码为4位</p>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>
    <footer class="flex-row flex-align-c flex-justify-c wlm-dialog-fixfooter">
      <el-button size="small" @click="saveDialogSubmit" type="primary">保存</el-button>
    </footer>
  </el-dialog>
  <div class="wlm-table">
    <div class="wlm-table-hearder-btn">
      <el-button size="small" type="primary" @click="dialogTableVisible = true;initChooseUser.closable = true;">添加店员</el-button>
    </div>
    <div class="wlm-table-header">
      <el-form :model="tableFormatData.userTable.files" size="small" label-width="80px" class="retail-form" label-position="right">
        <!-- <el-form-item label="门店名称：" class="search">
                    <el-input v-model="tableFormatData.userTable.files.nickname" placeholder="请输入门店名称" style="width:160px;"></el-input>
                </el-form-item> -->
        <el-form-item label="店员姓名：" class="search">
          <el-input v-model="tableFormatData.userTable.files.name" placeholder="请输入店员姓名" style="width:160px;"></el-input>
        </el-form-item>
        <el-form-item label="" class="filter-btns">
          <el-button v-waves type="primary" @click="filesSerch">筛选</el-button>
          <el-button type="text" @click="filesEmpty">清空筛选条件</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="wlm-table-content">
      <el-table :ref="tableFormatData.userTable.key" :data="tableFormatData.userTable.tableData" @selection-change="handleSelectionChange" style="width: 100%">
        <el-table-column type="selection" width="55">
        </el-table-column>
           <el-table-column prop="name" label="店员ID" >
          <template slot-scope="scope">
            <span>{{scope.row.id}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="date" label="用户" >
          <template slot-scope="scope" v-if="scope.row.users">
            <img class="logo" :src="scope.row.users.avatarUrl">
            <span> {{scope.row.users.nickName}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="date" label="姓名" >
          <template slot-scope="scope">
            <router-link v-if="scope.row.users" tag="span" :to="{path:'/user/managementUserEdit', query:{user_id:scope.row.users.user_id}}">
              <span class="pointer">{{scope.row.name}}</span>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="联系方式" >
          <template slot-scope="scope">
            <span>{{scope.row.mobile}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="所属门店" >
          <template slot-scope="scope">
            <span v-if="scope.row.type=='0'">{{scope.row.store?scope.row.store.name:''}}</span>
            <span v-if="scope.row.type=='1'">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="权限" >
          <template slot-scope="scope">
            <span v-for="(item, index) in scope.row.power" :key="index">
              {{item==='hxorder'?'订单核销':item==='seedata'?'查看交易数据':item==='takenot'?'接收下单通知':item==='delivergoods'?'物流发货':item==='look_hx_order'?'核销记录':item==='look_self_order'?'自提记录':item==='look_card_order'?'卡包记录':item==='look_order'?'订单管理':item==='store_settlement_data'?'门店结算数据':'-'}} {{scope.row.power.length>=2&&index==0||scope.row.power.length-1>index?'-':''}}</span>
            <span v-if="!scope.row.power">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="状态" >
          <template slot-scope="scope">
            <el-switch :active-value="1" :inactive-value="0" @change="changeTableItem({id:scope.row.id,status:scope.row.status},formFormatData.api.change.status)" v-model="scope.row.status"> </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" >
          <template slot-scope="scope">
            <div class="operation-group">
              <el-button class="wlm-text" type="text" @click="initChooseUser.closable = false;formFormatDialogEditEvt({id:scope.row.id,toggle:'dialogTableVisible'})">编辑</el-button>
              <div class="btn-line"></div>
              <el-button class="wlm-text" type="text" @click="delTableItem(scope.row.id)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-content flex-row flex-justify-b flex-align-c">
        <el-row class="pagination-btns">
          <el-checkbox class="check-all"  true-label="1" false-label="0" v-model="tableFormatData.userTable.files.checkall" @change="toggleSelection">全部</el-checkbox>
          <el-button class="right-8" :disabled="isGroup" size="mini" @click="delTableList">删除</el-button>
        </el-row>
        <el-pagination :disabled="!hasTableData" @size-change="listPageChange" @current-change="listPageChange" :current-page.sync="tableFormatData.userTable.pagination.page" :page-sizes="tableFormatData.userTable.pagination.pagesizes" :page-size.sync="tableFormatData.userTable.pagination.list_rows" layout="total, sizes, prev, pager, next, jumper" :total="hasTableData?tableFormatData.userTable.pagination.total : 0">
        </el-pagination>
      </div>
    </div>
  </div>
</div>
</template>

<script>
import {
  clerkEdit,
  clerkGet,
  clerkIndex,
  clerkDelete,
  selecStore,
  clerkStatus
} from '@/api/merchant'
import waves from '@/directive/waves' // Waves directive
import ChooseUser from '@/components/ChooseUser/index'
import mixins from '@/mixins/mixins'
import Cookies from 'js-cookie'
export default {
  mixins: [mixins.getters('Table'), mixins.getters('Form')],
  name: 'UserPlatform',
  components: {
    ChooseUser
  },
  directives: {
    waves
  },
  created() {
    selecStore({
      bus_id: this.$route.query.bus_id
    }).then((response) => {
      const {
        data: {
          data: msgData = {}
        }
      } = response
      //   this.storeListFind = msgData
      this.selecStoreData = msgData
    })
  },
  computed: {
    //代理端不需要申请直播
    powerdata(){
      return Cookies.get("agent_id")?
      [
        {label:'订单核销',value:'hxorder'}, 
        {label:'查看交易数据',value:'seedata'},
         {label:'店员管理',value:'addsal'}, 
         {label:'消息通知',value:'takemsg'},
         {label:'上传商品',value:'management'},
         {label:'预约管理',value:'reserve'},
         {label:'物流发货',value:'delivergoods'},
         {label:'核销记录',value:'look_hx_order'},
         {label:'自提记录',value:'look_self_order'},
         {label:'卡包记录',value:'look_card_order'},
         {label:'订单管理',value:'look_order'},
         {label:'门店结算数据',value:'store_settlement_data'},
         ]
         :
         [{label:'订单核销',value:'hxorder'},
         {label:'查看交易数据',value:'seedata'},
          {label:'店员管理',value:'addsal'}, 
          {label:'消息通知',value:'takemsg'},
          {label:'上传商品',value:'management'},
          {label:'预约管理',value:'reserve'},
          {label:'申请直播',value:'applylive'},
          {label:'物流发货',value:'delivergoods'},
         {label:'核销记录',value:'look_hx_order'},
         {label:'自提记录',value:'look_self_order'},
         {label:'卡包记录',value:'look_card_order'},
         {label:'订单管理',value:'look_order'},
          {label:'门店结算数据',value:'store_settlement_data'},
          ]
    }
  },
  data() {
    return {
      passwordCopy: '',
      passwordType: 'password',
      initChooseUser: {
        closable: true,
        initList: []
      },
      dialogTableVisible: false,
      selecUseData: [],
      selecStoreData: [],
      formFormatData: {
        key: 'user',
        model: {
          noCreateEdit: false,
          hasMessage: false,
          closeDialog: false,
          bindDialog: 'dialogTableVisible'
        },
        api: {
          editForm: {
            api: clerkGet,
            params: {
              bus_id: this.$route.query.bus_id
            }
          },
          submitForm: clerkEdit,
          change: {
            status: {
              key: 'status',
              api: clerkStatus
            }
          }
        },
        formData: {
          bus_id: this.$route.query.bus_id,
          store_id: '',
          mid: '',
          nickName: '',
          name: '',
          mobile: '',
          type: 0,
          power: [],
          password: '',
          status: 1
        },
        rules: {
          password: [{
            required: true,
            message: '请输入核销密码',
            trigger: 'blur'
          }]
        }
      },
      tableFormatData: {
        current: 'userTable',
        userTable: {
          key: 'userTable',
          api: {
            getList: clerkIndex,
            delList: clerkDelete
          },
          tableData: [],
          files: {
            name: '',
            ids: [],
            checkall: '0',
            Recycle: '1'
          },
          pagination: {
            page: 1,
            list_rows: 10,
            pagesizes: [10, 20, 50],
            total: 0
          }
        }
      }
    }
  },
  methods: {
    changeCodeF() {
      this.$nextTick(() => {
        if (this.formFormatData.formData.password !== null) {
          this.formFormatData.formData.password = this.formFormatData.formData.password.replace(/[^\d]/g, '')
        }
      })
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
    },
    dialogOpen() {
      // this.$nextTick(() => {
      //   console.log(this.formFormatData.formData.password)
      // })
    },
    saveDialogSubmit() {
      const { password } = this.formFormatData.formData
      if (password === this.passwordCopy) {
        this.formFormatData.formData.password = ''
      }
      if (this.formFormatData.formData.type === 0 && this.formFormatData.formData.store_id === '') {
        this.$message.error('请选择门店')
      } else {
        this.formFormatSubmit()
      }
    },
    saveDialogForm() {
      this.initChooseUser.initList = []
      this.passwordCopy = ''
      this.resetDialogFormData({ store_id: '', mid: '', nickName: '', name: '', mobile: '', type: 0, power: [], status: 1, bus_id: this.$route.query.bus_id, password: '' })
    },
    formFormatCallBack(data, type, response) {
      // this.filesSerch()
      if (type === 'editForm') {
        const { mid, name, nickName, password } = data
        this.initChooseUser.initList = [{ user_id: mid, nickName: nickName || name }]
        this.passwordCopy = password
      } else if (type === 'submitForm') {
        console.log(response, 'formFormatCallBack')
        const { data: { code, msg } } = response
        const hasId = Object.keys(this.$route.query).includes(this.formFormatData.api['editForm']['redirect'] || 'id')
        const isEdit = this.formFormatData.api['editForm'] && this.formFormatData.api['editForm']['api'] && ((this.$route.query && hasId) || (this.formFormatData.api['editForm']['params'] && this.formFormatData.api['editForm']['params']['always']))
        if (code === 1) {
          this.$message.success(isEdit && hasId ? '编辑成功' : '保存成功')
          this.dialogTableVisible = false
          this.getTableList()
        } else {
          this.$message.error(`${msg}`)
        }
        // else {
        //   this.$message.error(isEdit && hasId ? `${msg}` : `${msg}`)
        // }
      }
    },
    userChange(userlist) {
      const [{
        user_id
      }] = [...userlist]
      this.formFormatData.formData.mid = user_id
    }
  }
}
</script>

<style lang="scss" scoped>
.management-merchant {
  .logo {
    height: 32px;
    width: 32px;
    border-radius: 32px;
    vertical-align: middle;
  }
}
</style>
